from fastapi import FastAPI
from loguru import logger
from starlette.responses import JSONResponse

from app.exception_handlers.CustomExceptionHandler import CustomException, CreateUserException


def register_exception_handlers(app: FastAPI):
    """
    注册异常处理器
    :param app:
    :return:
    """

    @app.exception_handler(CustomException)
    async def custom_exception_handler(request, exc: CustomException):
        """
         注册自定义异常处理器
        :param request:
        :param exc:
        :return:
        """
        logger.error(f"捕获到CustomException: {exc.name}")
        return JSONResponse(
            status_code=418,
            content={"message": f"Oops! {exc.name} did something wrong"},
        )

    @app.exception_handler(CreateUserException)
    async def create_user_exception_handler(request, exc: CreateUserException):
        """
        注册自定义异常处理器
        :param request:
        :param exc:
        :return:
        """
        logger.error(f"捕获到CreateUserException: {exc.username}")
        return JSONResponse(
            status_code=419,
            content={"message": f"创建用户{exc.username}失败: {exc.err_msg}"},
        )